<template>
  <div class="class-setting-container">
    <h3 class="title">设置班级信息</h3>

    <el-tabs v-model="activeTab" type="card" class="custom-tabs">
      <!-- 1. 设置组成人员 -->
      <el-tab-pane label="设置组成人员" name="members">
        <div class="form-group">
          <h4 class="group-title">班级组成人员</h4>
          <el-form :model="form" label-width="120px" class="custom-form">
            <el-form-item label="通知人员" class="form-item">
              <el-select
                v-model="form.noticePersons"
                multiple
                placeholder="请选择通知人员（可多选）"
                class="custom-input"
                :disabled="memberOptions.length === 0"
              >
                <el-option
                  v-if="memberOptions.length === 0"
                  value=""
                  disabled
                >
                  暂无可用人员数据
                </el-option>
                <el-option
                  v-else
                  v-for="user in memberOptions"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出票人员" class="form-item">
              <el-select
                v-model="form.ticketPersons"
                multiple
                placeholder="请选择出票人员（可多选）"
                class="custom-input"
                :disabled="memberOptions.length === 0"
              >
                <el-option
                  v-if="memberOptions.length === 0"
                  value=""
                  disabled
                >
                  暂无可用人员数据
                </el-option>
                <el-option
                  v-else
                  v-for="user in memberOptions"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出证人员" class="form-item">
              <el-select
                v-model="form.certificatePersons"
                multiple
                placeholder="请选择出证人员（可多选）"
                class="custom-input"
                :disabled="memberOptions.length === 0"
              >
                <el-option
                  v-if="memberOptions.length === 0"
                  value=""
                  disabled
                >
                  暂无可用人员数据
                </el-option>
                <el-option
                  v-else
                  v-for="user in memberOptions"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="协助人员" class="form-item">
              <el-select
                v-model="form.assistPersons"
                multiple
                placeholder="请选择协助人员（可多选）"
                class="custom-input"
                :disabled="memberOptions.length === 0"
              >
                <el-option
                  v-if="memberOptions.length === 0"
                  value=""
                  disabled
                >
                  暂无可用人员数据
                </el-option>
                <el-option
                  v-else
                  v-for="user in memberOptions"
                  :key="user.userId"
                  :label="user.nickName || user.userName"
                  :value="user.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 2. 设置课程 -->
      <el-tab-pane label="设置课程" name="courses">
        <div class="form-group">
          <h4 class="group-title">培训课程</h4>
          <div class="table-wrapper">
            <el-table :data="courses" border style="width: 80%;" class="custom-table">
              <el-table-column label="课程名称">
                <template #default="scope">
                  <el-select v-model="scope.row.name" placeholder="请选择课程" class="custom-input">
                    <el-option label="前端开发" value="frontend"></el-option>
                    <el-option label="后端开发" value="backend"></el-option>
                    <el-option label="UI设计" value="ui"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="课程类型">
                <template #default="scope">
                  <el-select v-model="scope.row.type" placeholder="请选择类型" class="custom-input">
                    <el-option label="线上" value="online"></el-option>
                    <el-option label="线下" value="offline"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="学时">
                <template #default="scope">
                  <el-input v-model.number="scope.row.hours" placeholder="请输入学时" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="deleteRow(courses, scope.$index)" class="delete-btn">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addRow(courses, 'courses')" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 3. 设置教师 -->
      <el-tab-pane label="设置教师" name="teachers">
        <div class="form-group">
          <h4 class="group-title">培训教师</h4>
          <div class="table-wrapper">
            <el-table :data="teachers" border style="width: 60%;" class="custom-table">
              <el-table-column label="教师">
                <template #default="scope">
                  <el-select v-model="scope.row.name" placeholder="请选择教师" class="custom-input" :disabled="memberOptions.length === 0">
                    <el-option
                      v-if="memberOptions.length === 0"
                      value=""
                      disabled
                    >
                      暂无可用教师数据
                    </el-option>
                    <el-option
                      v-else
                      v-for="user in memberOptions"
                      :key="user.userId"
                      :label="user.nickName || user.userName"
                      :value="user.userId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="部门">
                <template #default="scope">
                  <el-input v-model="scope.row.department" placeholder="请输入部门" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="deleteRow(teachers, scope.$index)" class="delete-btn">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addRow(teachers, 'teachers')" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 4. 设置教材 -->
      <el-tab-pane label="设置教材" name="materials">
        <div class="form-group">
          <h4 class="group-title">培训教材</h4>
          <div class="table-wrapper">
            <el-table :data="materials" border style="width: 90%;" class="custom-table">
              <el-table-column label="教材名称">
                <template #default="scope">
                  <el-select v-model="scope.row.name" placeholder="请选择教材" class="custom-input">
                    <el-option label="Vue实战" value="vue"></el-option>
                    <el-option label="React入门" value="react"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="出版社">
                <template #default="scope">
                  <el-input v-model="scope.row.publisher" placeholder="请输入出版社" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="ISBN">
                <template #default="scope">
                  <el-input v-model="scope.row.isbn" placeholder="请输入ISBN" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="出版时间">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.publishTime"
                    type="date"
                    placeholder="选择日期"
                    class="custom-input"
                    @change="handleDateChange(scope.row, 'publishTime')"
                  ></el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="单价">
                <template #default="scope">
                  <el-input v-model.number="scope.row.price" placeholder="请输入单价" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="deleteRow(materials, scope.$index)" class="delete-btn">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addRow(materials, 'materials')" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 5. 设置耗材 -->
      <el-tab-pane label="设置耗材" name="supplies">
        <div class="form-group">
          <h4 class="group-title">培训耗材</h4>
          <div class="table-wrapper">
            <el-table :data="supplies" border style="width: 80%;" class="custom-table">
              <el-table-column label="耗材名称">
                <template #default="scope">
                  <el-select v-model="scope.row.name" placeholder="请选择耗材" class="custom-input">
                    <el-option label="笔记本" value="notebook"></el-option>
                    <el-option label="笔" value="pen"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量（按班级算）">
                <template #default="scope">
                  <el-input v-model.number="scope.row.classCount" placeholder="请输入数量" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="数量（按学员算）">
                <template #default="scope">
                  <el-input v-model.number="scope.row.studentCount" placeholder="请输入数量" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="合计">
                <template #default="scope">
                  <span class="total-text">{{ calculateSupplyTotal(scope.row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="说明">
                <template #default="scope">
                  <el-input v-model="scope.row.description" placeholder="请输入说明" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="deleteRow(supplies, scope.$index)" class="delete-btn">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addRow(supplies, 'supplies')" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 6. 设置考试 -->
      <el-tab-pane label="设置考试" name="exams">
        <div class="form-group">
          <h4 class="group-title">培训考试</h4>
          <div class="table-wrapper">
            <el-table :data="exams" border style="width: 90%;" class="custom-table">
              <el-table-column label="考试题组" width="250px">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.group"
                    placeholder="请选择考试"
                    class="custom-input"
                    @change="handlePaperConfigChange(scope.row, scope.row.group)"
                  >
                    <el-option
                      v-for="item in paperConfigOptions"
                      :key="item.paperConfigId"
                      :label="item.paperConfigName"
                      :value="item.paperConfigId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="单选题题量" >
                <template #default="scope">
                  <el-input v-model.number="scope.row.singleChoiceCount" placeholder="单选题题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="多选题题量">
                <template #default="scope">
                  <el-input v-model.number="scope.row.multipleChoiceCount" placeholder="多选题题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="判断题题量">
                <template #default="scope">
                  <el-input v-model.number="scope.row.judgmentCount" placeholder="判断题题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="合计题量">
                <template #default="scope">
                  <el-input v-model.number="scope.row.totalCount" placeholder="合计题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="分数合计">
                <template #default="scope">
                  <el-input v-model.number="scope.row.totalScore" placeholder="总分" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="deleteRow(exams, scope.$index)" class="delete-btn">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addRow(exams, 'exams')" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 7. 设置证书 -->
      <el-tab-pane label="设置证书" name="certificates">
        <div class="form-group">
          <h4 class="group-title">培训证书</h4>
          <div class="table-wrapper">
            <el-table :data="certificates" border style="width: 60%;" class="custom-table">
              <el-table-column label="证书">
                <template #default="scope">
                  <el-select v-model="scope.row.name" placeholder="请选择证书" class="custom-input">
                    <el-option label="前端工程师" value="fe"></el-option>
                    <el-option label="后端工程师" value="be"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="证书类型">
                <template #default="scope">
                  <el-input v-model="scope.row.type" placeholder="证书类型" class="custom-input"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button type="text" @click="deleteRow(certificates, scope.$index)" class="delete-btn">
                    <i class="el-icon-delete"></i> 删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addRow(certificates, 'certificates')" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 8. 设置培训计划 -->
      <el-tab-pane label="设置培训计划" name="plans">
        <div class="form-group">
          <h4 class="group-title">培训计划</h4>
          <div class="table-wrapper">
            <el-table :data="trainingPlans" border style="width: 100%;" class="custom-table">
              <el-table-column label="培训内容" width="200">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.content"
                    placeholder="请输入培训内容"
                    class="custom-input"
                    :disabled="!scope.row.isEditing"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="开始时间" width="160">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.startTime"
                    type="date"
                    placeholder="选择开始日期"
                    class="custom-input"
                    :disabled="!scope.row.isEditing"
                    @change="handleDateChange(scope.row, 'startTime')"
                  ></el-date-picker>
                </template>
              </el-table-column>

              <el-table-column label="结束时间" width="160">
                <template #default="scope">
                  <el-date-picker
                    v-model="scope.row.endTime"
                    type="date"
                    placeholder="选择结束日期"
                    class="custom-input"
                    :disabled="!scope.row.isEditing"
                    @change="handleDateChange(scope.row, 'endTime')"
                  ></el-date-picker>
                </template>
              </el-table-column>

              <el-table-column label="培训地点" width="160">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.location"
                    placeholder="请输入培训地点"
                    class="custom-input"
                    :disabled="!scope.row.isEditing"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="培训教师" width="150">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.teacher"
                    placeholder="请选择教师"
                    class="custom-input"
                    :disabled="memberOptions.length === 0 || !scope.row.isEditing"
                  >
                    <el-option
                      v-if="memberOptions.length === 0"
                      value=""
                      disabled
                    >
                      暂无可用教师数据
                    </el-option>
                    <el-option
                      v-else
                      v-for="user in memberOptions"
                      :key="user.userId"
                      :label="user.nickName || user.userName"
                      :value="user.userId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="说明" width="180">
                <template #default="scope">
                  <el-input
                    v-model="scope.row.description"
                    placeholder="请输入说明"
                    class="custom-input"
                    :disabled="!scope.row.isEditing"
                  ></el-input>
                </template>
              </el-table-column>

              <el-table-column label="操作">
                <template #default="scope">
                  <div v-if="!scope.row.isEditing">
                    <el-button type="text" @click="handleEdit(scope.$index)" class="edit-btn">
                      <i class="el-icon-edit"></i> 编辑
                    </el-button>
                    <el-button type="text" @click="deleteTrainingPlanRow(scope.$index)" class="delete-btn">
                      <i class="el-icon-delete"></i> 删除
                    </el-button>
                  </div>
                  <div v-else>
                    <el-button type="text" @click="handleSave(scope.$index)" class="save-btn">
                      <i class="el-icon-check"></i> 保存
                    </el-button>
                    <el-button type="text" @click="handleCancelEdit(scope.$index)" class="cancel-btn">
                      <i class="el-icon-refresh-right"></i> 取消
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-button type="text" @click="addTrainingPlanRow" class="add-btn">
            <i class="el-icon-plus"></i> 增加一项
          </el-button>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div class="button-group" v-if="activeTab !== 'plans'">
      <el-button @click="handleCancel" class="cancel-btn">取消</el-button>
      <el-button type="primary" @click="handleSubmit" class="submit-btn" :loading="submitLoading">提交</el-button>
    </div>
  </div>
</template>

<script>
import { queryNonMemberUsers } from "@/api/system/user"
import {
  savePeopleAllocation, queryPeopleAllocation,
  saveCourses, queryCourses,
  saveTeachers, queryTeachers,
  saveMaterials, queryMaterials,
  saveSupplies, querySupplies,
  setExam, queryExams,
  saveCertificates, queryCertificates,
  saveTrainingPlans, getTrainingClass, getExamInfoById,
} from "@/api/training/TrainingClass";
import {
  listByClassId, batchUpdateByClass, addTrainingSchedule, updateTrainingSchedule, delTrainingSchedule
} from "@/api/training/TrainingSchedule";
import {
  getPaperCofigList,
} from "@/api/examination/paperConfig";

import dayjs from 'dayjs';

export default {
  name: "ClassSetting",
  props: {
  },
  data() {
    return {
      classId: null,
      activeTab: "members",
      submitLoading: false,
      tabApiMap: {
        members: {
          api: savePeopleAllocation,
          dataKey: "form",
          queryApi: queryPeopleAllocation,
          successMsg: "班级组成人员保存成功",
          failMsg: "班级组成人员保存失败"
        },
        courses: {
          api: saveCourses,
          dataKey: "courses",
          queryApi: queryCourses,
          successMsg: "培训课程保存成功",
          failMsg: "培训课程保存失败"
        },
        teachers: {
          api: saveTeachers,
          dataKey: "teachers",
          queryApi: queryTeachers,
          successMsg: "培训教师保存成功",
          failMsg: "培训教师保存失败"
        },
        materials: {
          api: saveMaterials,
          dataKey: "materials",
          queryApi: queryMaterials,
          successMsg: "培训教材保存成功",
          failMsg: "培训教材保存失败"
        },
        supplies: {
          api: saveSupplies,
          dataKey: "supplies",
          queryApi: querySupplies,
          successMsg: "培训耗材保存成功",
          failMsg: "培训耗材保存失败"
        },
        exams: {
          api: setExam,
          dataKey: "exams",
          queryApi: queryExams,
          successMsg: "培训考试保存成功",
          failMsg: "培训考试保存失败"
        },
        certificates: {
          api: saveCertificates,
          dataKey: "certificates",
          queryApi: queryCertificates,
          successMsg: "培训证书保存成功",
          failMsg: "培训证书保存失败"
        },
        plans: {
          addApi: addTrainingSchedule,
          editApi: updateTrainingSchedule,
          deleteApi: delTrainingSchedule,
          dataKey: "trainingPlans",
          queryApi: listByClassId,
          successMsg: "培训计划保存成功",
          failMsg: "培训计划保存失败"
        }
      },
      idTabMap: {
        '1': 'members',
        '2': 'courses',
        '3': 'teachers',
        '4': 'materials',
        '5': 'supplies',
        '6': 'exams',
        '7': 'certificates',
        '8': 'plans'
      },
      memberOptions: [],
      form: {
        noticePersons: [],
        ticketPersons: [],
        certificatePersons: [],
        assistPersons: []
      },
      // 考试相关数据
      paperConfigOptions: [], // 考试题组选项
      exams: [{
        group: '',
        singleChoiceCount: null,
        multipleChoiceCount: null,
        judgmentCount: null,
        totalCount: null,
        totalScore: null
      }],
      // 其他数据
      courses: [{ name: "", type: "", hours: null }],
      teachers: [{ name: "", department: "" }],
      materials: [{ name: "", publisher: "", isbn: "", publishTime: null, price: null }],
      supplies: [{ name: "", classCount: null, studentCount: null, description: "" }],
      certificates: [{ name: "", type: "" }],
      trainingPlans: [],
      // 保存培训计划原始数据用于取消编辑
      originalTrainingPlans: [],
    };
  },
  computed: {
    calculateTotalHours() {
      return this.courses.reduce((total, c) => total + (c.hours || 0), 0);
    },
    calculateTotalMaterialPrice() {
      return this.materials.reduce((total, m) => total + (m.price || 0), 0);
    },
    calculateTotalExamQuestions() {
      return this.exams.reduce((total, e) => total + (e.totalCount || 0), 0);
    },
    calculateTotalExamScore() {
      return this.exams.reduce((total, e) => total + (e.totalScore || 0), 0);
    }
  },
  watch: {
    '$route.query.id': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId
        this.activeTab = this.idTabMap[params.id] || "members";
        this.loadTabData(this.activeTab);
      }
    },
    'activeTab': {
      handler(newTab) {
        this.loadTabData(newTab);
      }
    }
  },
  created() {
    this.getMembersList();
    this.getPaperConfigList();
  },
  methods: {
    async getPaperConfigList() {
      if (!this.classId) return;

      try {
        // 获取班级信息
        const classRes = await getTrainingClass(this.classId);
        // 获取班级关联的考试信息
        const classExamRes = await getExamInfoById(this.classId);
        console.log("班级考试信息:", classExamRes);

        // 填充考试表格数据
        if (classExamRes.code === 200 && Array.isArray(classExamRes.data) && classExamRes.data.length > 0) {
          this.exams = classExamRes.data.map(item => ({
            paperConfigId: item.paperConfigId,
            group: item.paperConfigId,
            singleChoiceCount: item.singleChoiceCount,
            multipleChoiceCount: item.multipleChoiceCount,
            judgmentCount: item.judgmentCount,
            totalCount: item.totalCount,
            totalScore: item.totalScore
          }));
        } else {
          this.exams = [{
            paperConfigId: "",
            group: '',
            singleChoiceCount: null,
            multipleChoiceCount: null,
            judgmentCount: null,
            totalCount: null,
            totalScore: null
          }];
        }

        // 获取项目关联的考试题组
        const res = await getPaperCofigList({
          trainingProjectId: classRes.data.trainingProject
        });
        console.log("考试题组列表:", res);

        if (res.code === 200 && Array.isArray(res.rows)) {
          this.paperConfigOptions = res.rows;
        }
      } catch (error) {
        console.error("获取考试配置失败:", error);
        this.$message.error("获取考试配置失败，请稍后重试");
      }
    },

    // 处理考试题组选择变化
    handlePaperConfigChange(row, paperConfigId) {
      if (!paperConfigId) return;

      // 找到选中的考试题组数据
      const selectedPaper = this.paperConfigOptions.find(
        item => item.paperConfigId === paperConfigId
      );

      if (selectedPaper) {
        // 自动回填数据
        row.paperConfigId = selectedPaper.paperConfigId;
        row.singleChoiceCount = selectedPaper.singleChoiceCount;
        row.multipleChoiceCount = selectedPaper.multipleChoiceCount;
        row.judgmentCount = selectedPaper.judgmentCount;
        row.totalCount = selectedPaper.totalCount;
        row.totalScore = selectedPaper.totalScore;
      }
    },

    getTeacherName(teacherId) {
      if (!teacherId) return '';
      const teacher = this.memberOptions.find(user => user.userId === teacherId);
      return teacher ? (teacher.nickName || teacher.userName || '未知教师') : '未知教师';
    },

    async getMembersList() {
      try {
        const userRes = await queryNonMemberUsers();
        this.memberOptions = userRes.rows || [];
        this.loadTabData(this.activeTab);
      } catch (error) {
        console.error("人员数据加载失败：", error);
        this.$message.error("人员信息加载失败，请稍后重试");
        this.memberOptions = [];
      }
    },

    handleDateChange(row, field) {
      if (field === 'startTime' && row.startTime && row.endTime) {
        if (dayjs(row.startTime).isAfter(dayjs(row.endTime))) {
          row.endTime = row.startTime;
        }
      }
    },

    handlePlansData(backendPlans) {
      if (!Array.isArray(backendPlans) || backendPlans.length === 0) {
        return [];
      }

      return backendPlans.map(plan => {
        let startTime = null;
        if (plan.scheduleStartTime) {
          const startDate = dayjs(plan.scheduleStartTime);
          if (startDate.isValid()) {
            startTime = startDate.toDate();
          }
        }

        let endTime = null;
        if (plan.scheduleEndTime) {
          const endDate = dayjs(plan.scheduleEndTime);
          if (endDate.isValid()) {
            endTime = endDate.toDate();
          }
        }

        return {
          content: plan.trainingContent || "",
          startTime: startTime,
          endTime: endTime,
          location: plan.scheduleAddress || "",
          teacher: Number(plan.scheduleTeacherId) || "",
          description: plan.scheduleRemarks || "",
          trainingContentId: plan.trainingContentId || "",
          personnelLimit: plan.personnelLimit || "",
          needReservation: plan.needReservation || "",
          isEditing: false,  // 从后端查询的数据默认不可编辑
          trainingScheduleId: plan.trainingScheduleId || ""
        };
      });
    },

    async loadTabData(tabName) {
      if (!this.classId || this.memberOptions.length === 0) return;

      const tabConfig = this.tabApiMap[tabName];
      if (!tabConfig || !tabConfig.queryApi) return;

      try {
        this.submitLoading = true;
        const response = await tabConfig.queryApi(this.classId);

        if (response && response.code === 200) {
          if (tabName === 'members') {
            this.handleMembersData(response.data.peopleList || []);
          } else if (tabName === 'plans') {
            const backendPlans = response.rows || [];
            this[tabConfig.dataKey] = this.handlePlansData(backendPlans);
            this.trainingPlans = this.handlePlansData(backendPlans);

            // 如果没有数据，添加一行默认数据但不进入编辑状态
            if (this.trainingPlans.length === 0) {
              this.trainingPlans.push({
                content: "",
                startTime: null,
                endTime: null,
                location: "",
                teacher: "",
                description: "",
                trainingContentId: "",
                personnelLimit: "",
                needReservation: "",
                isEditing: false,
                trainingScheduleId: ""
              });
            }
          } else if (tabName === 'teachers') {
            const backendTeachers = response.data.teachers || [];
            this.teachers = backendTeachers.length > 0
              ? backendTeachers.map(t => ({
                  name: t.teacherId || "",
                  department: t.department || ""
                }))
              : [{ name: "", department: "" }];
          } else if (tabName === 'exams') {
            // 考试数据加载
            if (response.data && Array.isArray(response.data)) {
              this.exams = response.data.map(item => ({
                paperConfigId: item.paperConfigId,
                group: item.paperConfigId,
                singleChoiceCount: item.singleChoiceCount,
                multipleChoiceCount: item.multipleChoiceCount,
                judgmentCount: item.judgmentCount,
                totalCount: item.totalCount,
                totalScore: item.totalScore
              }));
            } else {
              this.exams = [{
                paperConfigId: "",
                group: '',
                singleChoiceCount: null,
                multipleChoiceCount: null,
                judgmentCount: null,
                totalCount: null,
                totalScore: null
              }];
            }
          } else {
            this[tabConfig.dataKey] = response.data[tabConfig.dataKey] || this[tabConfig.dataKey];
          }
        }
      } catch (error) {
        console.error(`加载${tabName}数据失败：`, error);
        this.$message.error(`加载${this.getTabNameCN(tabName)}数据失败`);
      } finally {
        this.submitLoading = false;
      }
    },

    getTabNameCN(tabName) {
      const tabNames = {
        'members': '班级组成人员',
        'courses': '培训课程',
        'teachers': '培训教师',
        'materials': '培训教材',
        'supplies': '培训耗材',
        'exams': '培训考试',
        'certificates': '培训证书',
        'plans': '培训计划'
      };
      return tabNames[tabName] || tabName;
    },

    handleMembersData(peopleList) {
      const typeToFormField = {
        "1": "noticePersons",
        "2": "ticketPersons",
        "3": "certificatePersons",
        "4": "assistPersons"
      };

      Object.values(typeToFormField).forEach(field => {
        this.form[field] = [];
      });

      peopleList.forEach(allocItem => {
        const targetFormField = typeToFormField[allocItem.peopleType];
        if (!targetFormField) return;

        const rawUserIds = allocItem.peopleId?.trim() || "";
        const userIds = rawUserIds
          .split(";")
          .filter(id => id.trim())
          .map(id => Number(id))
          .filter(id => !isNaN(id) && this.memberOptions.some(user => user.userId === id));

        this.form[targetFormField] = userIds;
      });
    },

    // 增加培训计划行 - 新增行默认可编辑
    addTrainingPlanRow() {
      this.trainingPlans.push({
        content: "",
        startTime: null,
        endTime: null,
        location: "",
        teacher: "",
        description: "",
        trainingContentId: "",
        personnelLimit: "",
        needReservation: "",
        isEditing: true,  // 新增行默认可编辑
        trainingScheduleId: `temp_${Date.now()}_${Math.random().toString(36).slice(-4)}`
      });
    },

    async deleteTrainingPlanRow(index) {
      // if (this.trainingPlans.length > 1) {
      //   this.trainingPlans.splice(index, 1);
      // } else {
      //   this.$message.warning("至少保留一项培训计划");
      // }
      const plan = this.trainingPlans[index];
        if (plan.trainingScheduleId.includes('temp_')) {
          this.trainingPlans.splice(index, 1);
          this.$message.success("删除成功");
        } else {
          const response = await this.tabApiMap.plans.deleteApi(plan.trainingScheduleId);
          if (response && response.code === 200) {
            this.$message.success("删除成功");
            // 取消编辑状态
            this.$set(this.trainingPlans[index], 'isEditing', false);
            // 重新加载数据确保数据同步
            this.loadTabData('plans');
          } else {
            throw new Error(response?.msg || '保存失败');
          }
        }
    },

    // 编辑培训计划
    handleEdit(index) {
      // 保存原始数据用于取消编辑
      this.originalTrainingPlans[index] = { ...this.trainingPlans[index] };
      // 设置编辑状态
      this.$set(this.trainingPlans[index], 'isEditing', true);
    },

    // 保存编辑的培训计划
    async handleSave(index) {
      const plan = this.trainingPlans[index];

      // 验证数据
      if (!this.validatePlanData(plan)) {
        return;
      }

      this.submitLoading = true;

      try {
        // 格式化提交数据
        const formattedData = this.formatPlanData(plan);
        let response;

        // 根据ID判断是新增还是修改
        if (plan.trainingScheduleId.includes('temp_')) {
          // 新增操作 - 使用addApi
          response = await this.tabApiMap.plans.addApi(formattedData);
        } else {
          // 修改操作 - 使用editApi
          response = await this.tabApiMap.plans.editApi(formattedData);
        }

        if (response && response.code === 200) {
          this.$message.success("培训计划保存成功");
          // 取消编辑状态
          this.$set(this.trainingPlans[index], 'isEditing', false);
          // 重新加载数据确保数据同步
          this.loadTabData('plans');
        } else {
          throw new Error(response?.msg || '保存失败');
        }
      } catch (error) {
        this.$message.error(`保存失败：${error.message || '未知错误'}`);
        console.error('保存培训计划失败:', error);
      } finally {
        this.submitLoading = false;
      }
    },

    // 取消编辑培训计划
    handleCancelEdit(index) {
      const plan = this.trainingPlans[index];

      // 如果是临时数据（未保存的新增项），取消编辑时直接删除
      if (plan.trainingScheduleId.includes('temp_')) {
        this.trainingPlans.splice(index, 1);
      } else {
        // 恢复原始数据
        if (this.originalTrainingPlans[index]) {
          this.trainingPlans.splice(index, 1, this.originalTrainingPlans[index]);
        } else {
          // 取消编辑状态
          this.$set(this.trainingPlans[index], 'isEditing', false);
        }
      }
    },

    // 验证计划数据
    validatePlanData(plan) {
      // 检查必填项
      if (!plan.content || !plan.startTime || !plan.endTime || !plan.location || !plan.teacher) {
        this.$message.warning('培训内容、日期、地点和教师不能为空');
        return false;
      }

      // 检查时间顺序
      if (dayjs(plan.startTime).isAfter(dayjs(plan.endTime))) {
        this.$message.warning('培训开始时间不能晚于结束时间');
        return false;
      }

      return true;
    },

    // 格式化计划数据为接口所需格式
    formatPlanData(plan) {
      return {
        trainingClassId: this.classId,
        trainingContentId: plan.trainingContentId || `CONTENT_${Date.now()}_${Math.random().toString(36).slice(-4)}`,
        trainingContent: plan.content || "",
        scheduleStartTime: plan.startTime ? dayjs(plan.startTime).format('YYYY-MM-DD') : "",
        scheduleEndTime: plan.endTime ? dayjs(plan.endTime).format('YYYY-MM-DD') : "",
        scheduleAddress: plan.location || "",
        personnelLimit: plan.personnelLimit ? Number(plan.personnelLimit) : 25,
        scheduleTeacherId: plan.teacher || "",
        needReservation: plan.needReservation ? Number(plan.needReservation) : 1,
        scheduleRemarks: plan.description || "",
        trainingScheduleId: plan.trainingScheduleId
      };
    },

    addRow(arr, type) {
      const defaultRows = {
        courses: { name: "", type: "", hours: null },
        teachers: { name: "", department: "" },
        materials: { name: "", publisher: "", isbn: "", publishTime: null, price: null },
        supplies: { name: "", classCount: null, studentCount: null, description: "" },
        exams: {
          group: '',
          singleChoiceCount: null,
          multipleChoiceCount: null,
          judgmentCount: null,
          totalCount: null,
          totalScore: null
        },
        certificates: { name: "", type: "" }
      };
      arr.push({ ...defaultRows[type] });
    },

    deleteRow(arr, index) {
      arr.splice(index, 1);
      // if (arr.length > 1) arr.splice(index, 1);
      // else this.$message.warning("至少保留一项");
    },

    calculateSupplyTotal(row) {
      const studentCount = 10; // 实际应从班级信息中获取
      const total = (row.classCount || 0) + (row.studentCount || 0) * studentCount;
      row.total = total;
      return total;
    },

    async handleSubmit() {
      if (this.submitLoading) return;
      this.submitLoading = true;

      try {
        const currentTab = this.activeTab;
        const tabConfig = this.tabApiMap[currentTab];

        if (!tabConfig) {
          this.$message.error('未找到当前Tab的提交配置');
          return;
        }

        let tabData = this[tabConfig.dataKey];
        let submitData = { trainingClassId: this.classId };

        switch (currentTab) {
          case 'members':
            submitData.peopleList = [
              { peopleType: "1", peopleId: tabData.noticePersons.join(';') || "" },
              { peopleType: "2", peopleId: tabData.ticketPersons.join(';') || "" },
              { peopleType: "3", peopleId: tabData.certificatePersons.join(';') || "" },
              { peopleType: "4", peopleId: tabData.assistPersons.join(';') || "" }
            ];
            break;
          case 'teachers':
            submitData.data = tabData.map(t => ({
              teacherId: t.name || "",
              department: t.department || ""
            }));
            break;
          case 'plans':
            submitData.trainingSchedules = tabData.map(plan => ({
              trainingContentId: plan.trainingContentId || `CONTENT_${Date.now()}_${Math.random().toString(36).slice(-4)}`,
              trainingContent: plan.content || "",
              scheduleStartTime: plan.startTime ? dayjs(plan.startTime).format('YYYY-MM-DD') : "",
              scheduleEndTime: plan.endTime ? dayjs(plan.endTime).format('YYYY-MM-DD') : "",
              scheduleAddress: plan.location || "",
              personnelLimit: plan.personnelLimit ? Number(plan.personnelLimit) : 25,
              scheduleTeacherId: plan.teacher || "",
              needReservation: plan.needReservation ? Number(plan.needReservation) : 1,
              scheduleRemarks: plan.description || ""
            }));
            break;
          case 'supplies':
            submitData.data = tabData.map(item => ({
              ...item,
              total: this.calculateSupplyTotal(item)
            }));
            break;
          case 'materials':
            submitData.data = tabData.map(item => ({
              ...item,
              publishTime: item.publishTime ? dayjs(item.publishTime).format('YYYY-MM-DD') : ""
            }));
            break;
          case 'exams':
            let ids = "";
            let isArr = [];
            tabData.map(item => {
              isArr.push(item.paperConfigId)
              return 0;
            });
            ids = isArr.join(',')
            // 处理考试提交数据
            submitData = {
              trainingClassId: this.classId,
              examPaperIds: ids
            }
            console.log(submitData)
            break;
          default:
            submitData.data = tabData;
        }

        if (!this.validateTabData(currentTab, submitData.peopleList || submitData.data || tabData)) {
          return;
        }

        const response = await tabConfig.api(submitData);

        if (response && response.code === 200) {
          this.$message.success(tabConfig.successMsg);
          this.refreshTabData(currentTab);
          this.$emit('submitSuccess', { tab: currentTab, data: submitData });
        } else {
          throw new Error(response?.msg || '提交返回异常');
        }

      } catch (error) {
        const tabConfig = this.tabApiMap[this.activeTab];
        this.$message.error(`${tabConfig.failMsg}：${error.message || '未知错误'}`);
        console.error(`[${this.activeTab}] 提交失败:`, error);
      } finally {
        this.submitLoading = false;
      }
    },

    refreshTabData(tabName) {
      this.loadTabData(tabName);
    },

    validateTabData(tabName, data) {
      // if (!data || (Array.isArray(data) && data.length === 0)) {
      //   // this.$message.warning('请至少添加一条数据');
      //   return false;
      // }

      switch (tabName) {
        case 'members':
          const hasValidPerson = data.some(item => item.peopleId.trim() !== '');
          if (!hasValidPerson) {
            this.$message.warning('请至少选择一种类型的人员');
            return false;
          }
          break;
        case 'teachers':
          const invalidTeacher = data.some(item => {
            return !item.teacherId || !item.department;
          });
          if (invalidTeacher) {
            this.$message.warning('请选择教师并填写所属部门');
            return false;
          }
          break;
        case 'courses':
          const invalidCourse = data.some(item => {
            return !item.name || item.hours === null || item.hours <= 0;
          });
          if (invalidCourse) {
            this.$message.warning('课程名称不能为空且学时必须大于0');
            return false;
          }
          break;
        case 'materials':
          const invalidMaterial = data.some(item => {
            return !item.name || !item.publisher || !item.isbn || !item.publishTime;
          });
          if (invalidMaterial) {
            this.$message.warning('教材名称、出版社、ISBN和出版时间不能为空');
            return false;
          }
          break;
        case 'exams':
          break;
        case 'certificates':
          const invalidCertificate = data.some(item => !item.name || !item.type);
          if (invalidCertificate) {
            this.$message.warning('证书名称和类型不能为空');
            return false;
          }
          break;
        case 'plans':
          const invalidPlan = data.some(item => {
            const isRequiredEmpty = !item.content || !item.startTime || !item.endTime || !item.location || !item.teacher;

            let isTimeInvalid = false;
            if (item.startTime && item.endTime) {
              if (dayjs(item.startTime).isAfter(dayjs(item.endTime))) {
                isTimeInvalid = true;
              }
            }

            return isRequiredEmpty || isTimeInvalid;
          });

          if (invalidPlan) {
            const hasTimeOrderError = data.some(item => {
              return item.startTime && item.endTime &&
                dayjs(item.startTime).isAfter(dayjs(item.endTime));
            });

            if (hasTimeOrderError) {
              this.$message.warning('培训开始时间不能晚于结束时间');
            } else {
              this.$message.warning('培训内容、日期、地点和教师不能为空');
            }
            return false;
          }
          break;
      }

      return true;
    },

    handleCancel() {
      this.$emit("cancel");
    }
  }
};
</script>

<style scoped>
.class-setting-container {
  padding: 30px;
  margin: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
}

.title {
  text-align: center;
  margin-bottom: 32px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  position: relative;
}
.title::after {
  content: "";
  display: block;
  width: 80px;
  height: 3px;
  background: #165DFF;
  margin: 12px auto 0;
  border-radius: 2px;
}

.custom-tabs {
  margin-bottom: 24px;
}
.custom-tabs .el-tabs__item {
  padding: 12px 24px;
  font-size: 15px;
  color: #666;
}
.custom-tabs .el-tabs__item.is-active {
  color: #165DFF;
  font-weight: 500;
}
.custom-tabs .el-tabs__active-bar {
  background-color: #165DFF;
  height: 3px;
}
.custom-tabs .el-tabs__content {
  padding-top: 20px;
}

.form-group {
  margin-bottom: 32px;
}
.group-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
  padding-left: 8px;
  border-left: 4px solid #165DFF;
}

.custom-form .form-item {
  margin-bottom: 20px;
}
.custom-input {
  width: 100%;
  height: 36px;
  border-radius: 4px;
}
.custom-input .el-input__inner,
.custom-input .el-select__input {
  padding: 0 12px;
  height: 36px;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  margin: 16px 0;
}

.custom-table {
  border-color: #f0f0f0;
}
.custom-table th {
  background-color: #f5f7fa;
  color: #444;
  font-weight: 500;
  font-size: 14px;
}
.custom-table td {
  color: #666;
  font-size: 14px;
}
.custom-table .el-table__row:hover {
  background-color: #fafbfc;
}
.custom-table .el-table__cell {
  padding: 12px 8px;
}

.total-text {
  color: #165DFF;
  font-weight: 500;
}

.add-btn {
  color: #165DFF;
  font-size: 14px;
  margin-bottom: 16px;
}
.add-btn i {
  margin-right: 4px;
}
.add-btn:hover {
  color: #0E42D2;
  text-decoration: none;
}

.delete-btn {
  color: #999;
  font-size: 14px;
}
.delete-btn i {
  margin-right: 4px;
}
.delete-btn:hover {
  color: #F56C6C;
  text-decoration: none;
}

.edit-btn {
  color: #165DFF;
  font-size: 14px;
  margin-right: 10px;
}
.edit-btn i {
  margin-right: 4px;
}
.edit-btn:hover {
  color: #0E42D2;
  text-decoration: none;
}

.save-btn {
  color: #4CAF50;
  font-size: 14px;
  margin-right: 10px;
}
.save-btn i {
  margin-right: 4px;
}
.save-btn:hover {
  color: #388E3C;
  text-decoration: none;
}

.cancel-btn {
  color: #F56C6C;
  font-size: 14px;
}
.cancel-btn i {
  margin-right: 4px;
}
.cancel-btn:hover {
  color: #D32F2F;
  text-decoration: none;
}

.button-group {
  text-align: center;
  margin-top: 40px;
}
.cancel-btn {
  padding: 8px 24px;
  font-size: 14px;
  margin-right: 16px;
}
.submit-btn {
  padding: 8px 32px;
  font-size: 14px;
  background-color: #165DFF;
  border-color: #165DFF;
}
.submit-btn:hover {
  background-color: #0E42D2;
  border-color: #0E42D2;
}

@media (max-width: 768px) {
  .class-setting-container {
    padding: 20px 15px;
    margin: 10px;
  }
  .custom-tabs .el-tabs__item {
    padding: 10px 16px;
    font-size: 14px;
  }
  .button-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 0 15px;
  }
  .cancel-btn, .submit-btn {
    width: 100%;
    margin-right: 0;
  }
}
</style>
